import {
  getSaleRecord
} from '../../api/sale'
import {
  SALE_RECORD_LIST,
  SALE_RECORD_CURRENT_ROW,
  SALE_RECORD_DATA_COUNT,
  SALE_RECORD_HISTORY_DATA,
  SALE_RECORD_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    saleRecordList: [],
    saleRecordDataCount: null,
    pageSize: 20,
    saleRecordHistoryData: [],
    row: {
      uname: '',
      dname: '',
      cpa: '',
      cpv: '',
      ycpv: '',
      cps: '',
      cpsb: '',
      ctime: ''
    }
  },
  getters: {
    saleRecordList: state => state.saleRecordList
  },
  mutations: {
    [SALE_RECORD_LIST] (state, data) {
      state.saleRecordList = data
    },
    [SALE_RECORD_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [SALE_RECORD_DATA_COUNT] (state, data) {
      state.saleRecordDataCount = data
    },
    [SALE_RECORD_HISTORY_DATA] (state, data) {
      state.saleRecordHistoryData = data
    },
    [SALE_RECORD_UPLOAD_LIST] (state, data) {
      state.saleRecordList = state.saleRecordList.push(data)
    }
  },
  actions: {
    async getSaleRecordList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getSaleRecord(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          uname: item.uname ? item.uname : '-',
          dname: item.dname ? item.dname : '-',
          cpa: item.cpa,
          cpv: item.cpv,
          ycpv: item.ycpv,
          cps: item.cps,
          cpsb: item.cpsb,
          ctime: item.ctime
        }]
      })
      commit(SALE_RECORD_LIST, newData)
      commit(SALE_RECORD_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.saleRecord.pageSize) {
        commit(SALE_RECORD_HISTORY_DATA, newData)
      } else {
        commit(SALE_RECORD_HISTORY_DATA, newData.slice(0, rootState.saleRecord.pageSize))
      }
    },
    // async updateSaleRecordData ({ commit, rootState }, playload) {
    //   let data = {}
    //   if (Object.keys(playload).length > 0) {
    //     data = playload
    //   }
    //   await editeSaleRecord(data)
    // },
    async getSaleRecordCurrentRow ({ commit, rootState }, row) {
      commit(SALE_RECORD_CURRENT_ROW, row)
    },
    async changeSaleRecordPage ({ commit, rootState }, index) {
      let data = rootState.saleRecord.saleRecordList
      let _start = (index - 1) * rootState.saleRecord.pageSize
      let _end = index * rootState.saleRecord.pageSize
      commit(SALE_RECORD_HISTORY_DATA, data.slice(_start, _end))
    },
    async getSaleRecordUploadList ({ commit, rootState }, uploadList) {
      commit(SALE_RECORD_UPLOAD_LIST, uploadList)
    }
  }
}
